using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BuffDamageShield:BuffBase {

	public override string spriteName => "damage shield";

	static GameObject effectPrefab => _effectPrefab ? _effectPrefab : Resources.Load<GameObject>("DamageShieldEffect");
	static GameObject _effectPrefab;

	DamageShieldEffectCnotroller effect;

	public BuffDamageShield(BuffSlot slot,Mob mob) : base(slot,mob) {
		effect=Object.Instantiate(effectPrefab,mob.transform).GetComponent<DamageShieldEffectCnotroller>();
	}
	protected override void SubscribeEvents() {
		base.SubscribeEvents();
		damageSubscriber.SubscribeSingle(mob,OnProjectileHit);
	}
	protected override void UnsubscribeEvents() {
		base.UnsubscribeEvents();
		damageSubscriber.UnsubscribeSingle(mob,OnProjectileHit);
	}

	static EventSubscriber<DamageEventArgs> damageSubscriber = new EventSubscriber<DamageEventArgs>();
	static BuffDamageShield() {
		Mob.LateDamaging+=damageSubscriber.TargetEventHandler;
	}
	const float damagePerStack = 50f;
	public void OnProjectileHit(object _sender,DamageEventArgs e) {
		Mob sender = _sender as Mob;
		if(e.stat.amount>=stacks*damagePerStack) {
			e.stat.amount.AddAdd(-stacks*damagePerStack,float.MaxValue);
			effect.OnBreak();
			RemoveSelf();
		} else {
			if(e.stat.attackerProjectile&&e.stat.damageType==DamageType.Projectile) {
				Projectile attackerProjectile = e.stat.attackerProjectile;
				if(attackerProjectile.timePenetrated>=Mathf.FloorToInt(attackerProjectile.stat.penetration)) {
					attackerProjectile.stat.penetration.AddAdd(1,float.MaxValue);
					Vector2 normal = mob.collider.bounds.center-attackerProjectile.transform.position;
					attackerProjectile.velocity=Vector2.Reflect(attackerProjectile.velocity,normal);
				}
			}
			effect.OnHit();
			stacks-=e.stat.amount/damagePerStack;
			e.stat.amount=0;
		}

	}

	protected override void Update() {
		base.Update();
		if(_stacks<=0) RemoveSelf();
	}

	protected override void OnRemove() {
		base.OnRemove();
		Object.Destroy(effect.gameObject);
	}

}
